
//
//  SubmitOrderController.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/25.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "SubmitOrderController.h"

#import "LXAddressManagerViewController.h"

#import "AddressCell.h"

#import "ShopcartScrollCell.h"

#import "GreenBeanCell.h"

#import "ShopCartCouponCell.h"

#import "SubmitOrderBottomTool.h"

#import "AddCouponViewController.h"

#import <math.h>


@interface SubmitOrderController ()<UITableViewDelegate,UITableViewDataSource,SubmitOrderBottomToolDelegate,LXAddressManagerViewControllerDelegate,AddCouponViewControllerDelegate>{
    NSInteger _discountMode;//0:不使用绿豆和优惠券 1:使用绿豆 2:使用优惠券
    CGFloat _usedGreenBeans;//使用的绿豆数
}
@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic,strong)SubmitOrderBottomTool * bottomTool;

@property(nonatomic,strong)id  address;

@property(nonatomic,assign)CGFloat couponPrice;

@property(nonatomic,strong)CouponModel * coupon;

@end

@implementation SubmitOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.couponPrice = 0;
    _discountMode = 0;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomTool];
    [self.bottomTool setTotalPrice:[ShopCartManager calculateSelectedPrice] freight:0];
    [self xw_registerBackInteractiveTransitionWithDirection:XWInteractiveTransitionGestureDirectionRight transitonBlock:^(CGPoint startPoint) {
        [self.navigationController popViewControllerAnimated:YES];
    } edgeSpacing:100];
    [[LXDataManager manager] getAddrListWithComplete:^(BOOL success, id res) {
        if(success){
            NSMutableDictionary * mdic = [NSMutableDictionary dictionary];
            for (AddressModel * add in res) {
                if([add.def_addr isEqualToString:@"1"]){
                    [mdic setObject:add.mobile forKey:@"ship_mobile"];
                    [mdic setObject:[NSString stringWithFormat:@"%@%@%@",add.province,add.city,add.district] forKey:@"ship_addr"];
                    [mdic setObject:add.name forKey:@"ship_name"];
                    self.address = mdic;
                }
            }
            [self.tableView reloadData];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setUpNavi];
    self.tableView.contentInset = (UIEdgeInsets){-10,0,0,0};
    self.bottomTool.y = ScreenHeight - self.bottomTool.height - 64-54;
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

-(void)setUpNavi{
    [super setUpNavi];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"订单详情";
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 2?2:1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if(indexPath.section==0){
        AddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AddressCell"];
        if(!cell){
            cell = [[AddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddressCell"];
        }
        if(self.address){
            cell.address = self.address;
        }
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    else if(indexPath.section == 1){
        ShopcartScrollCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ShopcartScrollCell"];
        if(!cell){
            cell = [[ShopcartScrollCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShopcartScrollCell"];
        }
        cell.count = [ShopCartManager shareManager].selectedProduct.count;
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    else if (indexPath.section == 2){
        if(indexPath.row == 0){
            GreenBeanCell * cell = [tableView dequeueReusableCellWithIdentifier:@"GreenBeanCell"];
            if(!cell){
                cell = [[GreenBeanCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GreenBeanCell"];
            }
            [cell.backgroundImageView addRadius:0];
            cell.backgroundImageView.transform = CGAffineTransformIdentity;
            cell.backgroundImageView.image = [UIImage imageNamed:@"brokerage_bg02"];
            [self addCellHeight:cell.cellHeight indexPath:indexPath];
            cell.backgroundImageView.transform = CGAffineTransformRotate(cell.backgroundImageView.transform, M_PI);
            cell.enableUnderLine = YES;
            [self addCellHeight:cell.cellHeight indexPath:indexPath];
            __block MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"Loading...";
            [ShopCartManager calculateSelectedPriceWithGreenBeanComplete:^(CGFloat totalPrice, CGFloat discountPrice ,CGFloat userBean) {
                cell.l3.text = [NSString stringWithFormat:@"%.0f",userBean];
                cell.inputGreenBeans = (discountPrice<userBean)?discountPrice:userBean;
                cell.t1.text = [NSString stringWithFormat:@"可抵:%.2f个",cell.inputGreenBeans];
                
                CGFloat freight = (totalPrice)>59?0:10;
                self.bottomTool.freightLabel.text = [NSString stringWithFormat:@"(含运费:%.0f元)",freight];
                CGFloat price = (totalPrice+freight) +(_discountMode==1?-1:0)*(userBean/100.0) +(_discountMode==2?-1:0)*self.couponPrice;
                _usedGreenBeans = userBean;
                self.bottomTool.totalPrice.text = [NSString stringWithFormat:@"%.2f",price];
                [hud hide:YES];
               
            }];
            
            
            cell.selectedBtn.selected = _discountMode==1?YES:NO;
            cell.handleCallBack = ^(UIButton * btn){
                btn.selected=!btn.selected;
                _discountMode = btn.selected?1:0;
                [self.tableView reloadData];
            };
            return cell;
        }
        else{
            ShopCartCouponCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ShopCartCouponCell"];
            if(!cell){
                cell = [[ShopCartCouponCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShopCartCouponCell"];
            }
            cell.cellHeight = 50;
            [cell.backgroundImageView addRadius:0];
            cell.backgroundImageView.transform = CGAffineTransformIdentity;
           
            
            cell.backgroundImageView.image = [UIImage imageNamed:@"brokerage_bg02"];
            [self addCellHeight:cell.cellHeight indexPath:indexPath];
            cell.userIcon.hidden = YES;
            cell.nameLabel.text = @"优惠券";
            
            cell.showSubTeam = YES;
            cell.enableUnderLine = NO;
            cell.nameLabel.font = [UIFont systemFontOfSize:17];
            cell.subUser.font = [UIFont systemFontOfSize:17];
            cell.nameLabel.textColor = RGBColor(96,96,96);
            cell.subUser.textColor = RGBColor(96,96,96);
            [self addCellHeight:cell.cellHeight indexPath:indexPath];
            
            cell.subUser.text = self.couponPrice==0?@"未使用":[NSString stringWithFormat:@"%.2f",self.couponPrice];
            cell.selectedBtn.selected = _discountMode==2?YES:NO;
            cell.handleCallBack = ^(UIButton * btn){
                btn.selected=!btn.selected;
                _discountMode = btn.selected?2:0;
                [self.tableView reloadData];
            };
            return cell;
        }
        
    }
    else{
        UITableViewCell * cell = [[UITableViewCell alloc] init];
        cell.textLabel.text = [NSString stringWithFormat:@"%ld组-----%ld行",indexPath.section,indexPath.row];
        [self addCellHeight:50 indexPath:indexPath];
        return cell;
    }
    return nil;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        LXAddressManagerViewController * vc = [[LXAddressManagerViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.delegate = self;
    }
    if(indexPath.section == 2){
        if(indexPath.row == 1){
            AddCouponViewController * vc = [[AddCouponViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            vc.delegate = self;
        }
    }
}

-(void)AddCouponViewController:(AddCouponViewController *)vc didSelectedCoupon:(CouponModel *)coupon{
    self.couponPrice = coupon?[coupon.face_price floatValue]:0;
    self.coupon = coupon;
    [self.tableView reloadData];
}

-(void)DidSelectedContect:(id)address{
    self.address = address;
}

-(UITableView*)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = globalMargin;
    }
    return _tableView;
}


-(SubmitOrderBottomTool*)bottomTool{
    if(_bottomTool == nil){
        _bottomTool = [[SubmitOrderBottomTool alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        _bottomTool.y = ScreenHeight - _bottomTool.height;
        _bottomTool.backgroundColor = [UIColor whiteColor];
        _bottomTool.delegate = self;
    }
    return _bottomTool;
}


-(void)SubmitOrderBottomTool:(SubmitOrderBottomTool *)tool didClickSubmitButton:(UIButton *)button{
    if([self.address allKeys].count != 0){
        NSMutableDictionary * mDic = [NSMutableDictionary dictionaryWithDictionary:self.address];
        [mDic setValue:User_id  forKey:@"user_id"];    //用户id
        [mDic setObject:@([ShopCartManager numberOfProducts])                   forKey:@"product_num"];//商品数量
        [mDic setObject:@"0" forKey:@"cost_freight"];//物流费用
        [mDic setObject:@([ShopCartManager calculateSelectedPrice])                        forKey:@"cost_item"];//商品金额
        [mDic setObject:@([ShopCartManager calculateSelectedPrice])                         forKey:@"total_amount"];//总价格
        [mDic setObject:@"1" forKey:@"payment"];//支付方式
        [mDic setValue:[ShopCartManager format] forKey:@"product"];//商品
        
        if(_discountMode!=0){
            [mDic setValue:@(_discountMode) forKey:@"lesstype"];
            [mDic setValue:_discountMode==1?@(_usedGreenBeans):self.coupon.t_id forKey:@"lessnum"];
        }
        [[LXDataManager manager] getOrderIDWithPrama:mDic complete:^(BOOL success, id res) {
            if(success){
                NSString * orderStr = res[@"data"][@"order_id"];
                if(orderStr!=nil){
                    [self.view alertWithTitle:@"选择支付方式" mesege:@"" buttons:@[@"支付宝"] handle:^(NSInteger buttonIndex) {
                        [ShopCartManager payForOrderID:orderStr price:[tool.totalPrice.text floatValue] desc:[ShopCartManager formatName] complete:^(BOOL success) {
                            if(success){
                                [self.view alertWithTitle:@"提示" mesege:@"支付成功" buttons:@[@"好的"] handle:^(NSInteger buttonIndex) {
                                    [self.view dismissAlert];
                                }];
                            }else{
                                [self.view alertWithTitle:@"提示" mesege:@"支付失败" buttons:@[@"好的"] handle:^(NSInteger buttonIndex) {
                                    [self.view dismissAlert];
                                }];
                            }
                        }];
                    }];
                }
                else{
                    [self.view alertWithTitle:@"提示" mesege:@"订单生成失败" buttons:@[@"????"] handle:^(NSInteger buttonIndex) {
                        [self.view dismissAlert];
                    }];
                }
            }
        }];
    }else{
        [self.view alertWithTitle:@"" mesege:@"联系方式不完整请完善" buttons:@[@"知道了"] handle:^(NSInteger buttonIndex) {
            
        }];
    }
}



@end
